<template>
  <div v-loading="loading">
    <Header :title="t('flypass.template_theme')" />
    <el-card class="card">
      <el-tabs v-model="activeTab">
        <el-tab-pane :name="topic.topicId" :label="topic.topicName" v-for="(topic, index) in topics">
          <div class="px-5 pt-4 text-right">
            <el-button type="danger" icon="delete" @click="() => confirmDeleteTopic(topics![index].topicId)">{{ t('flypass.delete-theme') }}</el-button>
          </div>
          <div class="templates-container">
            <div class="template" v-for="(template, index) in topic.templatesInfoVo" @mouseenter="() => onMouseEnter(template)" @mouseleave="() => template.showBackdrop = false">
              <img  :src="baseurl + '/tempres/' + template.thumbUrl" alt="" >
              <Transition name="fade">
                <div class="image-background" v-show="template.showBackdrop">  
                  <el-button type="primary" icon="edit" @click="() => onEdit(template)">{{ t('common.edit') }}</el-button>
                  <el-button type="danger" icon="delete" v-if="index === topic.templatesInfoVo.length - 1" @click="() => confirmDeleteTemplate(template.templateId)">{{ t('common.delete') }}</el-button>
                </div>
              </Transition>
              <span>{{ t('cmp.page_level') }} {{  template.level }}</span>
            </div>
            <div class="new-template" @click="newTemplate">
              <svg-icon icon-class="OutlinedPlus" class-name="plus-icon"></svg-icon>
              <span>{{ t('flypass.add-new-template') }}</span>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane disabled>
          <template #label>
            <el-input :maxlength="maxLength.topicName" :placeholder="t('flypass.press-enter-to-add-new-topic')" style="width: 250px" ref="input" v-if="showNewTopicInput" size="small" v-model="newTopicName" v-clickoutside="onClickOutside" @keydown.enter="requestNewTopic"/>
            <el-button v-else size="small" type="primary" icon="plus" @click="showInput">{{ t('flypass.new-theme') }}</el-button>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { getAllTopicsAndTemplates, newTopic, deleteTopic } from '@/api/topic/topic';
import Header from '../components/header.vue';
import { ElMessageBox, ElMessage } from '@toms/element-ui'
import { Topic, TopicStatus, TemplateInfo } from '@/api/topic/topicModel';
import { usePassStore } from '@/store/modules/pass';
import { deleteTemplate } from '@/api/pass/template';
import { useTopic } from '@/views/pass-center/topic/useTopic';
import { maxLength } from '@/api/topic/rules';

defineOptions({ name: 'TopicAll' });

const store = usePassStore()
const { push } = useRouter()
const { t } = useI18n()
const { setShowBackdrop, editTemplate, confirmDeleteTemplate, loading } = useTopic(getData)
const baseurl = import.meta.env.VITE_APP_PROXY
const input = ref(null)
let isMounted = false 



onMounted(async () => {
  await getData()
  activeTab.value = topics.value[0].topicId
  isMounted = true
})

onActivated(() => {  
  if(isMounted) {    
    getData()
  }
})

const activeTab = ref(0)
const topics = ref<Topic[]>([])
const currentTopic = computed(():Topic | undefined => {  
  return topics.value.find(topic => topic.topicId === activeTab.value)
})
// 获取主题和模版列表
async function getData() {
  topics.value = await getAllTopicsAndTemplates()
  topics.value.forEach(t => {    
    t.templatesInfoVo.forEach(template => {
      template.thumbUrl += `?t=${new Date().getTime()}`
    })
    setShowBackdrop(t.templatesInfoVo)
  })
}

const showNewTopicInput = ref(false)
const newTopicName = ref('')
async function showInput() {
  showNewTopicInput.value = true
  await nextTick()
  input.value?.focus()
}

async function requestNewTopic() {
  loading.value = true
  await newTopic(newTopicName.value)
  loading.value = false
  showNewTopicInput.value = false
  newTopicName.value = ''
  await getData()  
  activeTab.value = topics.value[topics.value.length - 1].topicId
}

async function confirmDeleteTopic(topicId: number) {
  await ElMessageBox.confirm(
    t('flypass.delete-warning'),
    t('common.prompt'),
    {      
      type: 'warning',
    })
  loading.value = true
  const result = await deleteTopic(topicId)
  if(result) {
    ElMessage({
    type: 'success',
    message: t('common.message.operation_success')
    })
    await getData()
  } else {
    ElMessage({
      type: 'error', 
      message: t('cmp.msg_deleteFailed')
    })
  }
  loading.value = false
}

function onMouseEnter(template: TemplateInfo) {  
  template.showBackdrop = true
} 

function onClickOutside() {
  showNewTopicInput.value = false
  newTopicName.value = ''
}

function newTemplate() {
  if(currentTopic.value) {
    store.setTemplateLevel(currentTopic.value.templatesInfoVo.length)
    store.setTopicId(currentTopic.value.topicId)  
  }  
  push({path: '/pass-design/new', query:{topicId: currentTopic.value?.topicId}})
}

function onEdit(template: TemplateInfo) { 
  const topicId = currentTopic.value?.topicId
  if(topicId) {
    editTemplate(template, topicId)  
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>